<?php
/**
* init datetime for create/update fields
* 
*/
class TimestampBehavior extends CActiveRecordBehavior
{
    public $attributeCreationDatetime = 'creation_datetime';
    public $attributeUpdateDatetime = 'last_update';
    
    /**
     * Responds to {@link CActiveRecord::onBeforeSave} event.
     * Overrides this method if you want to handle the corresponding event of the {@link CBehavior::owner owner}.
     * You may set {@link CModelEvent::isValid} to be false to quit the saving process.
     * @param CModelEvent $event event parameter
     */
    public function beforeSave($event)
    {
        if (!$this->getOwner()->hasAttribute($this->attributeCreationDatetime)) {
            throw new CDbException(Yii::t('app', 'Attribute {att} not exist', array('{att}'=>$this->attributeCreationDatetime)));
            return false;
        } elseif (!$this->getOwner()->hasAttribute($this->attributeUpdateDatetime)) {
            throw new CDbException(Yii::t('app', 'Attribute {att} not exist', array('{att}'=>$this->attributeUpdateDatetime)));
            return false;
        }
        if ($event->isValid && $this->getOwner()->isNewRecord) {
            $this->getOwner()->{$this->attributeCreationDatetime} = date('Y-m-d H:i:s');//new CDbExpression('LOCALTIMESTAMP');
        }
        $this->getOwner()->{$this->attributeUpdateDatetime} = date('Y-m-d H:i:s');//new CDbExpression('LOCALTIMESTAMP');
    }
}
